package chromosomes;

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(sort_chromosomes get_canonical_chromosomes get_chromosomes_with_sequences);



use strict;
use warnings;
use DBI;
use DBD::Pg;
use Carp;
use FindBin;
#_________________________________________________________________________________________

#	sort_chromosomes

#			Sort list of chromosomes from 1 to 99 etc. then from X, Y onwards

#_________________________________________________________________________________________
sub sort_chromosomes
{
	#
	# order chromosomes
	#
	my (@sorted_chromosomes, @num_chromosomes, @alphanum_chromosomes);
	{
		# add chromosomes with numbers sorted first
		for (@_)
		{
			if (/^[\d\-]+$/)
			{
				push (@num_chromosomes, $_)
			}
			else
			{
				push (@alphanum_chromosomes, $_)
			}
		}

		# sort numeric chromosomes by number
		@sorted_chromosomes = sort {$a <=> $b} @num_chromosomes;

		# sort alphanumeric chromosome by length, so that X and Y come out first
		push(@sorted_chromosomes, sort {length($a) <=> length ($b) or $a cmp $b}
														@alphanum_chromosomes);
	}
	return @sorted_chromosomes;
}

#_________________________________________________________________________________________

#	get_canonical_chromosomes

#			Get list of sorted chromosomes which include 0-9 and X, Y, Z, W

#_________________________________________________________________________________________
sub get_canonical_chromosomes($$)
{
	my ($dbh, $species) = @_;
	my $cmd = <<"PL/SQLCMD";
		SELECT
			DISTINCT ON (chromosome)
			chromosome
		FROM
			taxon.gene_loci NATURAL join
            ens_id
		WHERE
            species = '$species' AND 
			chromosome ~ '^[0-9XYZW]+\$';
PL/SQLCMD
	my $chromosomes = $dbh->selectall_arrayref($cmd);

	return sort_chromosomes map {$_->[0]} (@$chromosomes);

}

sub get_chromosomes_with_sequences($$$)
{
	my ($dbh, $species, $seq_dir) = @_;
	my @chromosome_names;
	my @chromosome_files = glob("$seq_dir/chromosome.*.fa");
	for my $chromosome_file(@chromosome_files)
	{
		$chromosome_file =~ /chromosome\.(.+)\.fa/ or 
			croak "Error:\n\tStrange chromosome file [$chromosome_file]\n";
		push(@chromosome_names,  $1);
	}
	return @chromosome_names;
}





1;
